<script lang="ts" setup>
  import { reactive, ref, watch } from "vue"
  import pageHeader from '@/components/PageHeader/index.vue'
  import { saveOrUpdateProject,getProjectById } from '@/api/project'
  import storeModule from '@/views/store/table/index.vue'

  import {validateIdcard, validatePhone} from '@/utils/validate'
  import type { FormInstance, FormRules } from 'element-plus'
  import useFile from '@/hooks/useFile'
  import useForm from '@/hooks/useForm'
  import CustomerSelect1 from '@/components/CustomerSelect1/index.vue'
  import AdminSelect from '@/components/AdminSelect/index.vue'


  const formEl = ref<FormInstance>()
  const form = ref<any>({
    isEnable:true,
    isSupportChange: false
  })
  const { handleSubmit, loading, id, back } = useForm({formType: 'page'})
  const rules: FormRules = {
    name: [
      { required: true, message: '请输入项目名称', trigger: 'change' },
    ],
    status: [
      { required: true, message: '请输入状态', trigger: 'change' },
    ],
    settlementCycle: [
      { required: true, message: '请选择费用结算周期', trigger: 'change' },
    ],
    settlementType: [
      { required: true, message: '请选择费用结算方式', trigger: 'change' },
    ],
    projectLeaderId: [
      { required: true, message: '请选择项目负责人', trigger: 'change' },
    ],
    projectLiaisonPersonId: [
      { 
        required: true, 
        message: '请选择项目对接人', 
        trigger: 'change',
        validator: (rule, value, callback) => {
          // 如果是新增选项，检查projectLiaisonPersonName是否有值
          if (form.value.isNewLiaisonPerson) {
            if (!form.value.projectLiaisonPersonName) {
              callback(new Error('请输入项目对接人名称'))
            } else {
              callback()
            }
          } else {
            // 如果不是新增选项，则验证projectLiaisonPersonId
            if (!value) {
              callback(new Error('请选择项目对接人'))
            } else {
              callback()
            }
          }
        }
      }
    ],
    company:[
      { required: true, message: '请输入对接公司', trigger: 'change' },
    ],
    address: [
      { required: true, message: '请输入项目地址', trigger: 'change' },
    ],
  }

  const { beforeUpload, uploadUrl } = useFile({maxSize: 10, fileType: 'image'})

  const getDetail = () =>{
    loading.value = true
    getProjectById({id:id}).then((res)=>{
      form.value = res
      loading.value = false
    })
  }

  const selectCustomerChange = (val:any) => {
    console.log('选中的值：', val)
    console.log('是否为新增选项：', val.isNewOption)
    if(val.isNewOption){
      // 如果是新增选项，设置name并清空id
      form.value.projectLiaisonPersonName = val.value
      form.value.projectLiaisonPersonId = ''
      form.value.isNewLiaisonPerson = true
    } else {
      // 如果是选择已有选项，设置id并清空name
      form.value.projectLiaisonPersonId = val.value
      form.value.projectLiaisonPersonName = val.name?val.name:''
      form.value.isNewLiaisonPerson = false
    }
  }

  const handleSubmit1 = (api: any, formEl:any,  formData: any)  => {
  // console.log(formEl,'formEl')
  // console.log(formData,'form')
  
  // 处理contracts中的attachment数组
  if (formData.contracts && Array.isArray(formData.contracts)) {
    formData.contracts = formData.contracts.map(contract => {
      if (contract.attachment && Array.isArray(contract.attachment)) {
        return {
          ...contract,
          attachment: JSON.stringify(contract.attachment)
        }
      }
      return contract
    })
  }
  if(formData.isNewLiaisonPerson){
    formData.projectLiaisonPersonId = ''
  }
  
  handleSubmit(api, formEl, formData) 
}

  if(id) getDetail()
</script>

<template>
  <div class="app-container" v-loading="loading">
    <pageHeader title="新增项目" url="/account/franchisee"></pageHeader>

    <div class="page-main">
      <el-form ref="formEl" :rules="rules" :model="form" label-width="80px" label-position="top">
        <el-row :gutter="20" class="form-card-main">
          <el-col :span="8">
            <el-form-item label="项目名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="项目对接公司" prop="company">
              <el-input v-model="form.company" placeholder="请输入"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="项目对接人">
              <CustomerSelect1 v-model="form.projectLiaisonPersonId" filterable :multiple="false" width="100%" @change="selectCustomerChange" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="费用结算方式" prop="settlementType">
              <el-select clearable v-model="form.settlementType" placeholder="请选择">
                  <el-option label="全包" :value="0"></el-option>
                  <el-option label="计件" :value="1"></el-option>
                </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="费用结算周期" prop="settlementCycle">
              <el-input v-model="form.settlementCycle" placeholder="请输入"></el-input>
              <!-- <el-select style="width:200px;" clearable v-model="form.settlementCycle" placeholder="请选择">
                  <el-option label="年月" :value="0"></el-option>
                  <el-option label="季度" :value="1"></el-option>
                </el-select> -->
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="状态" prop="status">
              <el-select clearable v-model="form.status" placeholder="请选择">
                  <el-option label="洽谈中" :value="0"></el-option>
                  <el-option label="进行中" :value="1"></el-option>
                  <el-option label="已结束" :value="2"></el-option>
                </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="项目对接人电话" >
              <el-input v-model="form.contactPersonMobile" placeholder="请输入"></el-input>
            </el-form-item>
          </el-col>
          
          <el-col :span="8">
            <el-form-item label="我方公司" >
              <el-input v-model="form.ourCompany" placeholder="请输入"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="项目负责人" prop="projectLeaderId">
              <AdminSelect v-model="form.projectLeaderId" filterable width="100%"/>
            </el-form-item>
          </el-col>
          
          
          <el-col :span="8">
            <el-form-item label="项目地址" prop="address">
              <el-input v-model="form.address" placeholder="请输入"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <storeModule v-model="form.contracts" title="合同"/>

        <el-row :gutter="20" class="form-card-btn-main">
          <el-col :span="8">
            <el-button type="primary" @click="handleSubmit1(saveOrUpdateProject, formEl, form)">确定</el-button>
            <el-button type="" @click="back">取消</el-button>
          </el-col>
        </el-row>
      </el-form>
    </div>
  </div>
</template>

<style lang="scss" scoped>
  .avatar{
    width: 30px;
    height: 30px;
  }
</style>
